import { Collapse, Modal, Typography } from 'antd';
import {
  Button,
  CheckBox,
  LoadPanel,
  NumberBox,
  SelectBox,
  TagBox,
  TextBox,
  Toolbar,
} from 'devextreme-react';
import { forwardRef, useCallback, useEffect, useRef, useState } from 'react';
import './index.less';
// import { Item, Toolbar } from "devextreme-react/data-grid";

import ReportModal from '@/components/ReportModal';
import AccountingVoucherPupop from '@/pages/accountingEntryTest/rightTables/components/accountingVoucherPupop';
import AssistPupop from '@/pages/components/AssistPupop';
import { msgError, msgInfo } from '@/utils/msg';
import {
  formatDateYYMMDD,
  getCpasPrimaryColor,
  getGridDefaultPageProps,
  tabBoxOnMultiTagPreparingOfProp,
} from '@/utils/pub';
import type { IColumnProps } from 'devextreme-react/data-grid';
import { Paging } from 'devextreme-react/data-grid';
import { Button as TextBoxButton } from 'devextreme-react/text-box';
import { Item } from 'devextreme-react/toolbar';
import type { LoadOptions } from 'devextreme/data';
import CustomStore from 'devextreme/data/custom_store';
import { useModel } from 'umi';
import SubjectPopup from '~/public/cpas-business/components-bs/SubjectPopup';
import { CpasIcon, DevGrid } from '~/public/cpas-ui';
import { consts } from '../consts';
import type {
  AdvQueryParam,
  FormQueryParams,
  ProjectOverallProps,
  RetDataInfo,
  SampleField,
  SampleSizeAndAmount,
  SampleStepInfo,
  SampleTable,
  WhereSqlParams
} from '../typing';
import {
  OverallMode
} from '../typing';
import {
  getIniSampleSizeAndAmount,
  getSampleSizeAndAmount,
} from './SampleParameter/NonStatSampleService';
import {
  generateYearMonths,
  getExportGridDataSource,
  getIniFormQueryParams,
  getItemNameByAdvQueryParams,
  getItemNameByFormQueryParams,
  getKMMCByAdvQueryParams,
  getOverallMode,
  getPzlxList,
  getSampleOverallWhereSQL,
  getSampleTypeColumns,
  getTableFieldNameInfo,
  selectFileAndExportDataToExcel,
  sqlTextFun,
  udpateRowsDataRnValue,
} from './samplingProjectOverallService';
import { getSampleTableList } from './samplingRecordPopupService';
import { SamplingSourcePopup } from './samplingSourcePopup';
import {
  getDataGridLoadSortFields,
  getRnColumn,
  getSampleSourceColumsOfExists,
  getSampleSourceFieldValues,
  getTextFieldValueIsKeyOfMsg,
  getWhereSqlByFilterAnd,
  loadSampleSourceDataListOnly,
  udpateSampleTableValue,
  updateSampleTableProps,
} from './samplingSourceService';
import {
  getPageInfoByLoadOptions,
  getRealTableName,
  getSortFiedsCantSort,
  textBoxSelectAll,
} from './service';
import AdvancedQueryPupop from './tools/advancedQueryPupop';

const { Text } = Typography;

/**
 * 抽样项目总休
 * @param props
 * @returns
 */
const SamplingProjectOverall = forwardRef(
  (
    props: {
      propsOfParams: ProjectOverallProps;
      sampleStepInfo?: SampleStepInfo;
      setSampleStepInfo?: (value: SampleStepInfo) => void;
    },
    ref: any,
  ) => {
    const propsOfParams = props.propsOfParams; //参数的属性值

    const sampleStepInfo = props.sampleStepInfo; //参数的属性值
    if (propsOfParams.curSampleTable == undefined) return null;
    const {
      isOverallAddMode,
      isOverallEditMode,
      isViewMode,
      isSelectMode,
      isSampleList,
      isSampleListManualAddMode,
    } = getOverallMode(propsOfParams);

    const [isNeedAccountingVouche, setIsNeedAccountingVouche] = useState<boolean>(false);

    const accountingVoucherPupopRef = useRef<any>(null);
    const [isNeedSamplingSourcePopup, setIsNeedSamplingSourcePopup] = useState<boolean>(false);

    const samplingSourcePopupRef = useRef<any>(null);
    const itemNameRef = useRef<any>(null); //抽样项目
    //当前查询数据的参数(导出时用到)
    const [dataParams, setDataParams] = useState<any>();

    const [loading, setLoading] = useState(false);
    const isExecuteQueryRef = useRef(false);

    // const { yearId, tableYearArr } = sampRecord1;

    const { initialState } = useModel('@@initialState');

    const { dbname } = initialState?.curPart as any;
    const { username } = initialState?.curUser as any;

    //界面查询的参数
    const [formQueryParams, setFormQueryParams] = useState<FormQueryParams>(() => {
      let iniFormQueryParams = getIniFormQueryParams();
      //如果属性中有传入的,就使用属性中的
      if (propsOfParams.curWhereSqlParams?.formQueryParams) {
        iniFormQueryParams = {
          ...iniFormQueryParams,
          ...propsOfParams.curWhereSqlParams?.formQueryParams,
        };
      }
      //结转凭证
      if (iniFormQueryParams.includeJzpz == undefined) {
        iniFormQueryParams.includeJzpz = false;
      }

      return iniFormQueryParams;
    });
    //参数查询(界面)
    //  const [paramsQueryData, setParamsQueryData] = useState<string>('');

    //查询区域是否打开
    const [isOpenQueryArea, setIsOpenQueryArea] = useState<boolean>(false);
    //高级查询
    const [isNeedAdvQuery, setIsNeedAdvQuery] = useState<boolean>(false);
    const [isAdvQuery, setIsAdvQuery] = useState<boolean>(
      propsOfParams.curWhereSqlParams?.isAdvQuery ?? false,
    );
    {
      /* 报表项目选择 */
    }
    const [isNeedReportModal, setIsNeedReportModal] = useState<boolean>(false);
    //高级查询显示的文本
    let iniAdvQueryText = '';
    if (
      isOverallEditMode &&
      propsOfParams.curWhereSqlParams?.isAdvQuery &&
      propsOfParams.curWhereSqlParams.advQueryParams.length
    ) {
      iniAdvQueryText = propsOfParams.curWhereSqlParams.advQueryParams
        .map((item) => sqlTextFun(item))
        .join(' ');
    }

    const [advQueryText, setAdvQueryText] = useState<string>(iniAdvQueryText);
    //高级查询参数
    const [advQueryParams, setAdvQueryParams] = useState<AdvQueryParam[]>(
      propsOfParams.curWhereSqlParams?.advQueryParams ?? [],
    );

    const assistPupopRef = useRef<any>(null);
    const advQueryPupopRef = useRef<any>(null);
    const reportModalRef = useRef<any>(null);

    const [isNeedAssist, setIsNeedAssist] = useState<boolean>(false);
    const [isNeedSubject, setIsNeedSubject] = useState<boolean>(false);

    const subjectRef = useRef<any>();
    //const devGridRef = useRef<any>(null);

    // const [pageIndex, setPageIndex] = useState<number>(0);
    // const [pageSize, setPageSize] = useState<number>(consts.defaultSampePageSize);

    const devGridSampleSourceDataRef = useRef<any>();

    const [sampleSourceTableDataSource, setSampleSourceTableDataSource] = useState<CustomStore>();
    const [sampleSourceDataColumns, setSampleSourceDataColumns] = useState<IColumnProps[]>([]);
    // const [sampleSourceFields, setSampleSourceFields] = useState<SampleField[]>([]);

    const [yearMonths, setYearMonths] = useState<string[]>([]);
    //凭证类型
    const [pzlxList, setPzlxList] = useState<any[]>([]);
    /*
        const [sampleSizeAndAmount, setSampleSizeAndAmount] = useState<SampleSizeAndAmount>(getIniSampleSizeAndAmount()) */
    const sampleSizeAndAmountRef = useRef<SampleSizeAndAmount>(getIniSampleSizeAndAmount()); //2024-11-27改为ref,不再渲染
    /**
     * 样本行数
     */
    const getSampleTotalCount = () => {
      return devGridSampleSourceDataRef.current?.instance?.getDataSource()?.totalCount() || 0;
    };

    useEffect(() => {
      //给赋值父组件方法
      if (ref) {
        ref.current = {
          getSampleTotalCount,
          sampleProjectOverallProps: propsOfParams,
          sampleSourceDataColumns,
          sampleSizeAndAmount: sampleSizeAndAmountRef.current,
          refreshData,
          itemNameRef,
        };
      }
    }, [sampleSourceDataColumns]);

    //自动查询数据
    const autoQueryData = useCallback(
      (isAdvQuery?: boolean) => {
        if (propsOfParams.isAutoQueryData) {
          //测试状态自动加载
          setTimeout(() => {
            loadSampleSourceDataList(
              propsOfParams.curSampleTable,
              propsOfParams.curSampleTable?.sampleAllFieldsArray,
              propsOfParams.curDataId,
              isAdvQuery,
              advQueryParams || [],
            );
          }, 250);
        }
      },
      [propsOfParams, propsOfParams.curSampleTable, propsOfParams.curDataId, advQueryParams],
    );
    //初始加载数据
    useEffect(() => {
      if (propsOfParams.curSampleTable && propsOfParams.curDataId) {
        loadSampleSourceInfo(propsOfParams.curSampleTable, propsOfParams.curDataId);

        if (propsOfParams.curSampleTable.isVoucher) {
          const yearMonths = generateYearMonths(propsOfParams.curDataId);
          setYearMonths(yearMonths);
          //如果有传入的值,优先使用
          formQueryParams.monthStartStr = formQueryParams.monthStartStr || yearMonths[0];
          formQueryParams.monthEndStr =
            formQueryParams.monthEndStr || yearMonths[yearMonths.length - 1];
          getPzlxList({ dbname, Data_ID: propsOfParams.curDataId }).then((pzlxList: any[]) => {
            pzlxList.unshift({ PZLX: '' });

            setPzlxList(pzlxList);
            autoQueryData(propsOfParams.curWhereSqlParams?.isAdvQuery);
          });
        } else {
          setAdvQueryText(advQueryParams?.map((item) => sqlTextFun(item)).join(' '));
          autoQueryData(propsOfParams.curWhereSqlParams?.isAdvQuery);
        }
      }
    }, [propsOfParams.curSampleTable, propsOfParams.curDataId, propsOfParams.sampleTableList]);

    //  修改基本的参数
    const changeFormQueryValue = (valKey: string, val: any) => {
      if (propsOfParams?.curWhereSqlParams && propsOfParams?.setCurWhereSqlParams) {
        (propsOfParams.curWhereSqlParams?.formQueryParams as any)[valKey] = val;
        propsOfParams.setCurWhereSqlParams({ ...propsOfParams.curWhereSqlParams } as any);
      }
      setFormQueryParams((oldData: any) => {
        const newData = { ...oldData };
        newData[valKey] = val;
        return newData;
      });
    };
    /**
     * 显示高级查询弹窗
     */
    async function showAdvQueryPopup() {
      setIsNeedAdvQuery(true);
      const tableName = getRealTableName(propsOfParams.curSampleTable?.tableName || '', {
        data_id: propsOfParams.curDataId,
      });
      const tableFieldNameInfo = await getTableFieldNameInfo(dbname, [tableName]);
      const interval = setInterval(() => {
        if (advQueryPupopRef.current) {
          clearInterval(interval);
          advQueryPupopRef.current.show({
            sampleTable: propsOfParams.curSampleTable,
            conditionsData: advQueryParams,
            tableFieldNameInfo,
            okCallback: (okData: AdvQueryParam[]) => {
              setIsAdvQuery(true);
              setAdvQueryParams(okData); //高级查询条件

              setIsNeedAdvQuery(false);

              setAdvQueryText(okData.map((item) => sqlTextFun(item)).join(' '));
              if (isOverallAddMode || isOverallEditMode) {
                if (propsOfParams.curSampleTable?.isVoucher) {
                  propsOfParams.curSampleItem.itemName = getItemNameByAdvQueryParams(okData);
                  propsOfParams.setCurSampleItem &&
                    propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });

                  //高级查询时,把科目名称也要写上,作为抽样项目
                  formQueryParams.kmmcStr = getKMMCByAdvQueryParams(okData);
                  changeFormQueryValue('kmmcStr', formQueryParams.kmmcStr);
                }
                //更新高级查询条件到 propsOfParams 20241202
                if (propsOfParams?.curWhereSqlParams && propsOfParams?.setCurWhereSqlParams) {
                  propsOfParams.curWhereSqlParams.advQueryParams = okData;
                  propsOfParams.setCurWhereSqlParams({ ...propsOfParams.curWhereSqlParams } as any);
                }
              }

              //查询
              loadSampleSourceDataList(
                propsOfParams.curSampleTable,
                propsOfParams.curSampleTable?.sampleAllFieldsArray,
                propsOfParams.curDataId,
                true,
                okData,
              );
              // createAdvQuerySqlText(okData);
            },
          });
        }
      }, 10);
    }
    function getToolbarItemOfQueryButtons() {
      return (
        <>
          {!isAdvQuery && (
            <div className="itemBoxDispaly">
              <Button
                text="查询"
                type="default"
                icon="find"
                style={{ marginTop: 0 }}
                width={95}
                height={32}
                onClick={() => {
                  if (propsOfParams.curSampleTable?.isVoucher) {
                    if (formQueryParams.jeFx == consts.JF_DF_Text) {
                      const len = propsOfParams.curSampleTable.sampleNumFieldsArray.filter((item) =>
                        consts.JFJE_DFJE_Array.includes(item),
                      ).length;

                      const fieldsArray = propsOfParams.curSampleTable?.sampleAllFieldsArray
                        .filter((item) =>
                          propsOfParams.curSampleTable?.sampleNumFieldsArray?.includes(
                            item.fieldName,
                          ),
                        )
                        .map((item) => item.fieldTitle);

                      let text = fieldsArray.join('、');
                      if (text) {
                        text = `样本源凭证表只设置了金额字段【${text}】,需要【借方金额】和【贷方金额】`;
                      } else {
                        text = `样本源凭证表需要设置金额字段【借方金额】和【贷方金额】`;
                      }
                      if (len !== consts.JFJE_DFJE_Array.length) {
                        Modal.error({
                          content: `不能选择【${consts.JF_DF_Text}】作为查询条件，${text}!`,
                          zIndex: 2000,
                        });
                        return;
                      }
                    }
                  }

                  loadSampleSourceDataList(
                    propsOfParams.curSampleTable,
                    propsOfParams.curSampleTable?.sampleAllFieldsArray,
                    propsOfParams.curDataId,
                    isAdvQuery,
                    advQueryParams,
                  );
                }}
              />
            </div>
          )}
          {isAdvQuery && propsOfParams.curSampleTable?.isVoucher && (
            <div className="itemBoxDispaly">
              <Button
                text="关闭高级"
                width={95}
                height={32}
                onClick={() => {
                  if (isOverallAddMode || isOverallEditMode) {
                    propsOfParams.curSampleItem.itemName =
                      getItemNameByFormQueryParams(formQueryParams);
                    if (propsOfParams.curWhereSqlParams) {
                      propsOfParams.curWhereSqlParams.isAdvQuery = false;
                      propsOfParams.curWhereSqlParams.advQueryParams.length = 0;
                    }
                    propsOfParams.setCurSampleItem &&
                      propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });
                  }
                  setIsAdvQuery(false);
                  setAdvQueryText('');
                }}
              />
            </div>
          )}
          <div className="itemBoxDispaly" style={{ marginTop: '8px' }}>
            <Button
              text="高级查询"
              type={isAdvQuery ? 'default' : 'normal'}
              width={95}
              height={32}
              onClick={() => {
                showAdvQueryPopup();
              }}
            />
          </div>
        </>
      );
    }
    function getNotQueryConditionHtml() {
      return (
        <div
          style={{ color: getCpasPrimaryColor(), cursor: 'pointer', marginTop: 8 }}
          onClick={() => showAdvQueryPopup()}
        >
          {consts.notQueryCondition}
        </div>
      );
    }
    //刷新数据
    function refreshData(inIsAdvQuery?: boolean, inAdvQueryParams?: AdvQueryParam[]) {
      loadSampleSourceDataList(
        propsOfParams.curSampleTable,
        propsOfParams.curSampleTable?.sampleAllFieldsArray,
        propsOfParams.curDataId,
        inIsAdvQuery || isAdvQuery,
        inAdvQueryParams || advQueryParams,
      );
    }
    function getSourceToolbar() {
      let html = null;
      if (isAdvQuery) {
        html = (
          <Toolbar>
            <Item location="before">{advQueryText || getNotQueryConditionHtml()}</Item>
            <Item location="before">{getToolbarItemOfQueryButtons()}</Item>
          </Toolbar>
        );
      } else {
        html = (
          <Toolbar>
            <Item location={'before'}>
              <div style={{ width: 'calc(100% - 8px)', display: 'flex', alignItems: 'center' }}>
                <div>
                  <div className="itemBoxDispaly" style={{ marginBottom: '8px' }}>
                    <div
                      style={{
                        width: '30px',
                        margin: '0 5px',
                      }}
                    >
                      金额
                    </div>

                    <div
                      className="itemBoxDispaly"
                      style={{ width: 290, justifyContent: 'space-between' }}
                    >
                      <SelectBox
                        width="100"
                        placeholder=""
                        dataSource={['', '借方', '贷方', '借或贷']}
                        dropDownOptions={{
                          width: '120px',
                        }}
                        value={formQueryParams.jeFx}
                        onValueChanged={(e: any) => {
                          console.log(e.value, '@@@ e.value');
                          changeFormQueryValue('jeFx', e.value);
                        }}
                      />
                      <SelectBox
                        width="70"
                        style={{
                          minWidth: formQueryParams.jeOperator == consts.betweenText ? 70 : 40,
                        }}
                        placeholder=""
                        dataSource={['', '<', '<=', '>', '>=', '=', '<>', consts.betweenText]}
                        value={formQueryParams.jeOperator}
                        onValueChanged={(e: any) => {
                          // console.log(e.value, '@@@ e.value');
                          changeFormQueryValue('jeOperator', e.value);
                        }}
                      />
                      <NumberBox
                        value={formQueryParams.jeStartValue}
                        width="100"
                        format={consts.numberFormat}
                        onFocusIn={textBoxSelectAll}
                        onValueChange={(value: any) => {
                          //console.log(value, '@@@');
                          changeFormQueryValue('jeStartValue', value);
                        }}
                        onEnterKey={() => refreshData()}
                      />
                      <NumberBox
                        onFocusIn={textBoxSelectAll}
                        value={formQueryParams.jeEndValue}
                        width="100"
                        visible={formQueryParams.jeOperator === consts.betweenText}
                        onValueChange={(value: any) => {
                          //console.log(value, '@@@');
                          changeFormQueryValue('jeEndValue', value);
                        }}
                        onEnterKey={() => refreshData()}
                      />
                    </div>
                  </div>

                  <div className="itemBoxDispaly">
                    <div
                      style={{
                        width: '30px',
                        margin: '0 5px',
                      }}
                    >
                      月份
                    </div>
                    <div
                      className="itemBoxDispaly"
                      style={{ width: 290, justifyContent: 'space-between' }}
                    >
                      <SelectBox
                        width="100"
                        placeholder=""
                        dataSource={yearMonths}
                        value={formQueryParams.monthStartStr}
                        onValueChanged={(e: any) => {
                          console.log(e.value, '@@@ e.value');
                          changeFormQueryValue('monthStartStr', e.value);
                        }}
                      />
                      <div style={{ margin: '0 8px' }}>至</div>
                      <SelectBox
                        width="100"
                        placeholder=""
                        dataSource={yearMonths}
                        value={formQueryParams.monthEndStr}
                        onValueChanged={(e: any) => {
                          console.log(e.value, '@@@ e.value');
                          changeFormQueryValue('monthEndStr', e.value);
                        }}
                      />
                    </div>
                  </div>
                </div>
              </div>
            </Item>

            <Item location="before" locateInMenu="auto">
              <div>
                <div className="itemBoxDispaly" style={{ marginBottom: '8px' }}>
                  <div
                    style={{
                      width: '60px',
                      margin: '0 5px',
                    }}
                  >
                    科目编号
                  </div>
                  <SelectBox
                    width="90"
                    style={{ marginRight: 5 }}
                    dataSource={consts.textOperatorArray}
                    value={formQueryParams.kmbhOperator}
                    placeholder="选择"
                    onValueChanged={(e: any) => {
                      console.log(e.value, '@@@ e.value');
                      changeFormQueryValue('kmbhOperator', e.value);
                    }}
                  />
                  <TextBox
                    // mode={passwordMode}
                    //placeholder='请输入科目编号'
                    value={formQueryParams.kmbhStr}
                    width={140}
                    onValueChange={(value: any) => {
                      //console.log(value, '@@@');
                      changeFormQueryValue('kmbhStr', value);
                    }}
                    onEnterKey={() => refreshData()}
                    hint={consts.multiSeparator}
                  />
                </div>
                <div className="itemBoxDispaly">
                  <div
                    style={{
                      width: '60px',
                      margin: '0 5px',
                    }}
                  >
                    对方科目
                  </div>
                  <div
                    className="itemBoxDispaly"
                    style={{ width: 240, justifyContent: 'space-between' }}
                  >
                    <SelectBox
                      width="90"
                      placeholder=""
                      style={{ marginRight: 5 }}
                      dataSource={consts.textOperatorArray}
                      value={formQueryParams.dfkmOperator}
                      onValueChanged={(e: any) => {
                        console.log(e.value, '@@@ e.value');
                        changeFormQueryValue('dfkmOperator', e.value);
                      }}
                    />
                    <TextBox
                      value={formQueryParams.dfkmStr}
                      width={140}
                      hint={consts.multiSeparator}
                      onValueChange={(value: any) => {
                        //console.log(value, '@@@');
                        changeFormQueryValue('dfkmStr', value);
                      }}
                      onEnterKey={() => refreshData()}
                    >
                      <TextBoxButton
                        name="text"
                        location="after"
                        options={{
                          height: 28,
                          icon: 'more',
                          stylingMode: 'outlined', //'text' | 'outlined' | 'contained';
                          onClick: () => {
                            setIsNeedSubject(true);
                            const interval = setInterval(() => {
                              if (subjectRef.current) {
                                clearInterval(interval);
                                subjectRef.current.show({
                                  title: '选择科目',
                                  dbname: dbname,
                                  Data_ID: propsOfParams.curDataId,
                                  isHasFZZ: false,
                                  editUser: username,
                                  // 选择 模式 0：单选 1：多选连机选择
                                  selectMode: '1',
                                  //  1：多选连机选择时是否进行递归选择默认是 true
                                  recursiveMultiple: false,
                                  // 是否为辅助账
                                  auxiliaryState: false,
                                  // 可以选择当前节点的科目
                                  isSelectSuperior: false,
                                  // 自动结转科目 默认选中的类型参数
                                  subjectType: 'periodEarly',
                                  okCallback: (r: any, v: any) => {
                                    // 科目审定明细 界面增加一级科目在业务组件 需做更改
                                    const kmmcData = v.map((item: any) => item.KMMC).join(',');
                                    changeFormQueryValue('dfkmStr', kmmcData);
                                    setIsNeedSubject(false);
                                    formQueryParams.dfkmStr = kmmcData;
                                    refreshData();
                                  },
                                });
                              }
                            }, 10);
                          },
                        }}
                      />
                    </TextBox>
                  </div>
                </div>
              </div>
            </Item>
            <Item location="before" locateInMenu="auto">
              <div>
                <div className="itemBoxDispaly" style={{ marginLeft: 25, marginTop: 5 }}>
                  <CheckBox
                    text="是否包含结转凭证"
                    hint="是否包含结转凭证"
                    style={{ marginLeft: 0 }}
                    value={formQueryParams.includeJzpz}
                    onValueChanged={(e: any) => {
                      changeFormQueryValue('includeJzpz', e.value);
                      formQueryParams.includeJzpz = e.value;
                      refreshData();
                    }}
                  />
                </div>

                <div className="itemBoxDispaly" style={{ marginTop: 15 }}>
                  <div
                    style={{
                      width: '33px',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      margin: '0 5px',
                    }}
                  >
                    摘要
                  </div>

                  <TextBox
                    // mode={passwordMode}
                    value={formQueryParams.zyStr}
                    width={150}
                    // valueChangeEvent='keyup'
                    onValueChange={(value: any) => {
                      //console.log(value, '@@@');
                      changeFormQueryValue('zyStr', value);
                    }}
                    hint={consts.multiSeparator}
                    onEnterKey={() => refreshData()}
                  />
                </div>
              </div>
            </Item>

            <Item location="before" locateInMenu="auto">
              <div>
                <div className="itemBoxDispaly" style={{ marginBottom: '8px' }}>
                  <div
                    style={{
                      width: '60px',
                      margin: '0 5px',
                    }}
                  >
                    核算项目
                  </div>
                  <TextBox
                    value={formQueryParams.hsxmStr}
                    width={180}
                    // valueChangeEvent='keyup'
                    onValueChange={(value: any) => {
                      //console.log(value, '@@@');
                      changeFormQueryValue('hsxmStr', value);
                      formQueryParams.hsxmStr = value;
                      if (isOverallAddMode || isOverallEditMode) {
                        propsOfParams.curSampleItem.itemName =
                          getItemNameByFormQueryParams(formQueryParams);
                        propsOfParams.setCurSampleItem &&
                          propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });
                      }
                      refreshData();
                    }}
                    onEnterKey={() => refreshData()}
                    hint={consts.multiSeparator}
                  // inputAttr={nameLabel}
                  >
                    <TextBoxButton
                      name="text"
                      location="after"
                      options={{
                        height: 28,
                        icon: 'more',
                        stylingMode: 'outlined', //'text' | 'outlined' | 'contained';
                        onClick: () => {
                          setIsNeedAssist(true);
                          const interval = setInterval(() => {
                            if (assistPupopRef.current) {
                              clearInterval(interval);
                              assistPupopRef.current.showAssistPupop({
                                setIsNeedAssist,
                                title: '选择辅助账',
                                dbname: dbname,
                                Data_ID: propsOfParams.curDataId,
                                isHasFZZ: false,
                                editUser: username,
                                // 选择 模式 0：单选 1：多选连机选择
                                selectMode: '1',
                                //  1：多选连机选择时是否进行递归选择默认是 true
                                recursiveMultiple: false,
                                okCallback: (r: any, v: any[]) => {
                                  if (v.filter((item) => item.IsEnd).length == 0) {
                                    return msgError('请选择末级辅助账');
                                  }
                                  // 科目审定明细 界面增加一级科目在业务组件 需做更改
                                  const displayNameData = v
                                    .map((item: any) => item.displayName)
                                    .join(';');
                                  console.log(r, v, displayNameData, '@@@');

                                  changeFormQueryValue('hsxmStr', displayNameData);
                                  setIsNeedAssist(false);
                                  formQueryParams.hsxmStr = displayNameData;

                                  if (isOverallAddMode || isOverallEditMode) {
                                    propsOfParams.curSampleItem.itemName =
                                      getItemNameByFormQueryParams(formQueryParams);
                                    propsOfParams.setCurSampleItem &&
                                      propsOfParams.setCurSampleItem({
                                        ...propsOfParams.curSampleItem,
                                      });
                                  }

                                  refreshData();
                                },
                              });
                            }
                          }, 10);
                        },
                      }}
                    />
                  </TextBox>
                </div>

                <div className="itemBoxDispaly">
                  <div style={{ width: '60px', margin: '0 5px' }}>凭证类型</div>
                  <SelectBox
                    width="180"
                    placeholder=""
                    dataSource={pzlxList}
                    displayExpr="PZLX"
                    valueExpr="PZLX"
                    hint={formQueryParams.pzlxStr}
                    value={formQueryParams.pzlxStr}
                    onValueChanged={(e: any) => {
                      console.log(e.value, '@@@ e.value.pzlxStr');
                      changeFormQueryValue('pzlxStr', e.value);
                    }}
                  />
                </div>
              </div>
            </Item>

            <Item location="before">{getToolbarItemOfQueryButtons()}</Item>
          </Toolbar>
        );
      }
      return html;
    }

    //  const textFieldsText = getFieldsTexts(props.curSampleTable.sampleAllFieldsArray, props.curSampleTable.sampleTextFieldsArray) || consts.curNoValue;
    // const numFieldsText = getFieldsTexts(props.curSampleTable.sampleAllFieldsArray, props.curSampleTable.sampleNumFieldsArray) || consts.curNoValue;

    /**
     * 样本列表手工增加样本
     */
    const getManualAddSampleColumn = useCallback(() => {
      const column: IColumnProps = {
        caption: '操作',
        width: 80,
        fixed: true,
        fixedPosition: 'left',
        type: 'buttons',
        buttons: [
          {
            name: 'manualAdd',
            // icon: RawSvgIconByDevExpress('icon-WORD'),
            text: '添加样本',
            cssClass: 'cursor-pointer',
            onClick: (e: any) => {
              //rowData=e.row.data
              propsOfParams.events?.onManualAddSample && propsOfParams.events.onManualAddSample(e);
              // console.log(e.row.data, '@@@');
            },
          },
        ],
      };
      return column;
    }, []);

    //加载样本源信息
    async function loadSampleSourceInfo(sampleTable: SampleTable, dataId: string) {
      const sampleSourceFields = sampleTable.sampleAllFieldsArray; // await getSampleSourceFields(dbname, sampleTable.tableName);
      const columns: any[] = [];
      columns.push(getRnColumn());
      if (isSampleList) {
        columns.push(...getSampleTypeColumns());
      }
      columns.push(...getSampleSourceColumsOfExists(sampleTable, sampleSourceFields, false, true));
      //样本列表手工增加样本
      if (propsOfParams.events?.onManualAddSample && !isViewMode) {
        columns.push(getManualAddSampleColumn());
      }
      setSampleSourceDataColumns(columns);
      setSampleSourceTableDataSource([] as any);
    }
    /**
     * 查询条件的参数
     * @returns
     */
    function getWhereSqlParams(
      isAdvQuery: boolean,
      advQueryParams: AdvQueryParam[],
    ): WhereSqlParams {
      return {
        dbname,
        isAdvQuery,
        advQueryParams,
        // accountInfoList: props.accountInfoList,
        yearMonths,
        formQueryParams, //: isAdvQuery ? getIniFormQueryParams() : formQueryParams,//高级查询时,用初始化的
      };
    }
    /**
     * 获取样本表
     * @returns
     */
    const loadSampleSourceDataList = useCallback(
      async (
        /* pageIndex: number, pageSize: number, */
        sampleTable?: SampleTable,
        sampleSourceFields?: SampleField[],
        dataId?: string,
        isAdvQuery?: boolean,
        advQueryParams?: AdvQueryParam[],
      ) => {
        if (!sampleTable?.tableName) return [];

        if (!sampleTable.isVoucher) {
          isAdvQuery = true; //固定写死,非凭证使用高级查询
        }
      /*   if (isExecuteQueryRef.current) {
         // msgError('数据加载中不能操作,请稍候...')
          return;
        } */
        isExecuteQueryRef.current = true;
        //查询条件

        const whereSqlParams = getWhereSqlParams(isAdvQuery || false, advQueryParams || []);

        if (isOverallAddMode || isOverallEditMode) {
          propsOfParams.curWhereSqlParams = whereSqlParams;
          propsOfParams.setCurWhereSqlParams && propsOfParams.setCurWhereSqlParams(whereSqlParams); //返回给 父组件
        }

        let whereSql = getSampleOverallWhereSQL(whereSqlParams); //获取sql

        if (propsOfParams.fixedWhereSql) {
          //固定sql条件
          whereSql += ' /*fixedWhereSql:*/  ' + propsOfParams.fixedWhereSql;
        }

        //setLoading(true)不 能加,会导致多次请求CustomStore
        const dataParams = {
          dbname,
          tableName: getRealTableName(sampleTable?.tableName, { data_id: dataId || '' }), //todo:要替换真值
          sortFields: sampleTable.sortFieldsArray.map((item) => `[${item}]`).join(','),
          fields: sampleSourceFields
            ? sampleSourceFields.map((item) => `[${item.fieldName}]`).join(',')
            : '',
          whereSql: whereSql || '',
        }; //数据参数
        setDataParams(dataParams);

        //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
        setSampleSourceTableDataSource(
          new CustomStore({
            key: 'rn',
            load: async (loadOptions: LoadOptions) => {
              const { pageIndex, pageSize } = getPageInfoByLoadOptions(loadOptions);
              let rowsData: any[] = [];
              const filterWhereSql = getWhereSqlByFilterAnd(loadOptions.filter);
              console.log('loadOptions.filter', loadOptions.filter);
              console.log('filterWhereSql', filterWhereSql);
              const dataField = (loadOptions as any).dataField;

              //点击表头的过滤器时,只查询
              if (dataField) {
                rowsData = await getSampleSourceFieldValues(
                  dbname,
                  sampleTable,
                  dataField,
                  dataId,
                  whereSql + filterWhereSql,
                );
                isExecuteQueryRef.current = false;
                return { data: rowsData, totalCount: rowsData.length };
              } else {
                //正常查询数据时

                const sortFields = loadOptions.sort
                  ? getDataGridLoadSortFields(loadOptions)
                  : dataParams.sortFields;
                if (getSortFiedsCantSort(sortFields)) {
                  msgError('此列不能排序!');
                  devGridSampleSourceDataRef.current.instance.clearSorting();
                  rowsData = devGridSampleSourceDataRef.current.instance.getDataSource()._items; //取原来的数据行
                } else {
                  rowsData = await loadSampleSourceDataListOnly(
                    dbname,
                    sampleTable,
                    pageIndex,
                    pageSize,
                    sampleSourceFields,
                    sortFields,
                    dataId,
                    whereSql + filterWhereSql,
                  );

                  //更新数据行号
                  udpateRowsDataRnValue(rowsData, pageIndex, pageSize, sampleSourceFields);

                  //过滤条件为空时,表示正常查询,需要加载样本数量和金额
                  if (
                    !filterWhereSql &&
                    [OverallMode.overallAdd, OverallMode.overallEdit].includes(
                      propsOfParams.overallMode,
                    )
                  ) {
                    getSampleSizeAndAmount({
                      projectOverallProps: { ...propsOfParams, curWhereSqlParams: whereSqlParams },
                    }).then((retData) => {
                      sampleSizeAndAmountRef.current = retData;
                      if (ref.current) {
                        ref.current.sampleSizeAndAmount = retData;
                      }
                    });
                  }
                }
                const retData2 = {
                  data: rowsData,
                  totalCount: rowsData.length ? rowsData[0].tc : 0,
                };

                //回调事件
                propsOfParams.events?.onLoadData &&
                  propsOfParams.events?.onLoadData({
                    rowsData: retData2.data,
                    totalCount: retData2.totalCount,
                    whereSqlParams: whereSqlParams,
                    fieldsFilterWhereSql: filterWhereSql,
                  });
                isExecuteQueryRef.current = false;
                return retData2;
              }
            },
          }),
        );

        return [];
        //  return retData.data;
      },
      [propsOfParams.curSampleTable, propsOfParams.curDataId, yearMonths, formQueryParams],
    );

    //查询条件的 右肩膀
    function onBeforeExportData(retDataInfo: RetDataInfo) {
      if (propsOfParams.events?.onBeforeExportData) {
        propsOfParams.events?.onBeforeExportData(retDataInfo);
      }
      udpateRowsDataRnValue(
        retDataInfo.rowsData,
        0,
        consts.maxExportCount,
        propsOfParams.curSampleTable?.sampleAllFieldsArray || [],
      );
    }
    function getQueryExtra() {
      //<CpasIcon type="icon-a-XLSXXLS" />
      return (
        <>
          <span
            title="全部导出"
            className="ac-refhresh-button"
            onClick={async (e) => {
              e.stopPropagation();
              setLoading(true);

              console.time('loadAllDevGridExport');
              let exportFileNameOnly =
                propsOfParams.exportFileNameOnly ||
                propsOfParams.curSampleTable?.tableTitle ||
                '样本数据';
              exportFileNameOnly = exportFileNameOnly.replace(/[\\\/:*?"<>|]/g, '');
              exportFileNameOnly = exportFileNameOnly + '-' + formatDateYYMMDD(new Date());

              await selectFileAndExportDataToExcel(
                sampleSourceDataColumns,
                dataParams,
                exportFileNameOnly + '.xlsx',
                onBeforeExportData,
              );

              console.timeEnd('loadAllDevGridExport');
              setLoading(false);
            }}
          >
            <CpasIcon type="icon-a-XLSXXLS" /> 导出
          </span>

          <span
            title="刷新"
            className="ac-refhresh-button iconfont icon-refresh"
            onClick={(e) => {
              e.stopPropagation();
              refreshData();
            }}
          />
        </>
      );
    }
    function getDivHeight() {
      if (isSampleList || isSampleListManualAddMode) {
        return '55vh';
      } else if (isSelectMode) {
        return '85%';
      } else {
        return '80vh';
      }
    }
    console.log('sampleTableList', propsOfParams.sampleTableList);
    return (
      <div className="SamplingProjectPopulation" style={{ height: getDivHeight() }}>
        {/* 样本源维护 */}
        {isNeedSamplingSourcePopup && <SamplingSourcePopup ref={samplingSourcePopupRef} />}
        {isNeedAdvQuery && <AdvancedQueryPupop ref={advQueryPupopRef} />}
        {/* 记账凭证 */}
        {isNeedAccountingVouche && (
          <AccountingVoucherPupop
            ref={accountingVoucherPupopRef}
            cellDblClickCallback={(rowData: any, curYear: any) => {
              msgInfo(`正在打开 明细账,请稍候...`);
              if (window.electronComponents) {
                const sessionParams = JSON.parse(window.sessionStorage.electronParams);
                const { sjxmbh, ZcbfID } = sessionParams.params;
                window.location.href = `cpas://OpenLocalFile/?fileName={UFCPAS4_PATH}/UFCPAS4.exe&params=UserCode={UserCode} UserPwd={UserPwd} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID} Functions=FM_103 FunParameters="Data_ID=${curYear},KMBH=${rowData.KMBH}"`;
              } else {
                console.error('window["electronComponents"] false');
              }
            }}
          />
        )}
        {/* 报表项目选择 */}
        {isNeedReportModal && (
          <ReportModal
            ref={reportModalRef}
            dbname={dbname}
            dataId={propsOfParams.curDataId}
            selectionMode={'single'}
            cancelCallback={() => setIsNeedReportModal(false)}
            okCallback={(itemNames: string[]) => {
              if (isOverallAddMode || isOverallEditMode) {
                propsOfParams.curSampleItem.itemName = itemNames[0];
                propsOfParams.setCurSampleItem &&
                  propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });
                setIsNeedReportModal(false);
              }
            }}
            modalProps={{ zIndex: 1501 }}
          />
        )}
        {isNeedAssist && <AssistPupop ref={assistPupopRef} />}
        {isNeedSubject && <SubjectPopup ref={subjectRef} />}

        <Toolbar visible={isOverallAddMode || isOverallEditMode}>
          <Item location="before" key="accountInfoList">
            <div style={{ marginLeft: 5, display: 'flex', alignItems: 'center' }}>
              <div>年度：</div>
              <SelectBox
                style={{ zIndex: 1 }}
                width={80}
                disabled={isOverallEditMode}
                dataSource={propsOfParams.accountInfoList}
                displayExpr="Data_ID" //displayName
                valueExpr="Data_ID"
                value={propsOfParams.curDataId}
                hint={
                  propsOfParams.accountInfoList.find(
                    (item) => item.Data_ID == propsOfParams.curDataId,
                  )?.displayName
                }
                // dropDownOptions={{ width: 300 }}

                onValueChange={(e: any) => {
                  if (isExecuteQueryRef.current) {
                    msgError('数据加载中不能操作,请稍候...')
                    return;
                  }
                  const newValue: string = e;
                  if (isOverallAddMode || isOverallEditMode) {
                    propsOfParams.curDataId = newValue;
                    changeFormQueryValue('dataId', newValue);
                    const yearMonths: string[] = generateYearMonths(newValue);
                    if (yearMonths.length) {
                      formQueryParams.monthStartStr = yearMonths[0];
                      changeFormQueryValue('monthStartStr', yearMonths[0]);

                      formQueryParams.monthEndStr = yearMonths[yearMonths.length - 1];
                      changeFormQueryValue('monthEndStr', yearMonths[yearMonths.length - 1]);
                    }
                    setYearMonths(yearMonths);
                    propsOfParams.setCurDataId && propsOfParams.setCurDataId(newValue);

                    getSampleTableList(dbname, newValue, propsOfParams.setSampleTableList).then(
                      (list) => (propsOfParams.sampleTableList = list),
                    );
                  }
                }}
              />
            </div>
          </Item>
          <Item location="before" key="sampleSourceList">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <a
                style={{ color: 'blue', textDecoration: 'underline' }}
                title="打开样本源维护"
                onClick={() => {
                  //console.log("样本源维护");
                  setIsNeedSamplingSourcePopup(true);
                  //用一个定时器来显示pupop
                  const interval = setInterval(() => {
                    if (samplingSourcePopupRef.current) {
                      clearInterval(interval);
                      samplingSourcePopupRef.current.show({
                        setIsNeedSamplingSourcePopup,
                        updateSampleTableList: (newSampleTableList: SampleTable[]) => {
                          // if(isOverallAddMode){
                          propsOfParams.sampleTableList = newSampleTableList;
                          propsOfParams.setSampleTableList &&
                            propsOfParams.setSampleTableList([...propsOfParams.sampleTableList]);
                          const newSampleTable = newSampleTableList.find(
                            (item) => item.tableName === propsOfParams.curSampleTable?.tableName,
                          );
                          if (newSampleTable) {
                            propsOfParams.curSampleTable = newSampleTable;
                            propsOfParams.setCurSampleTable &&
                              propsOfParams.setCurSampleTable({ ...propsOfParams.curSampleTable });
                          } else {
                            Modal.error({
                              zIndex: 5000,
                              content:
                                propsOfParams.curSampleTable?.tableTitle +
                                ' 已被删除,不可继续使用此表!',
                            });
                          }
                        },
                      });
                    }
                  }, 10);
                }}
              >
                样本源
              </a>
              ：
              <SelectBox
                readOnly={isOverallEditMode} //编辑模式不可修改,因为会导致表名发生变化,查询sql变化,找不到字段
                width={150}
                placeholder="请选择样本源"
                dataSource={propsOfParams.sampleTableList}
                dropDownOptions={{ width: 300 }}
                searchEnabled={true}
                displayExpr="tableTitle"
                valueExpr="tableName"
                hint={
                  propsOfParams.curSampleTable?.tableTitle +
                  (isOverallEditMode ? '(编辑状态不可修改)' : '')
                }
                value={propsOfParams.curSampleTable?.tableName}
                onValueChange={(e: any) => {
                  if (isExecuteQueryRef.current) {
                    msgError('数据加载中不能操作,请稍候...')
                    return;
                  }
                  const newValue: string = e;
                  if (isOverallAddMode || isOverallEditMode) {
                    const sampleTable = propsOfParams.sampleTableList.find(
                      (item) => item.tableName == newValue,
                    ) as SampleTable;
                    if (sampleTable) {
                      setIsAdvQuery(!sampleTable.isVoucher);
                      propsOfParams.curSampleTable = sampleTable;
                      propsOfParams.setCurSampleTable &&
                        propsOfParams.setCurSampleTable(sampleTable);
                      if (sampleTable.sampleTextFieldsArray.length == 0) {
                        msgError('没有抽样项目字段,请在当前界面设置!');
                      }
                    }
                    setAdvQueryParams([]); //清空高级查询条件
                    setAdvQueryText(''); //清空高级查询条件

                    //先赋值吧
                    propsOfParams.curWhereSqlParams = {
                      dbname,
                      yearMonths: propsOfParams.curWhereSqlParams?.yearMonths || [],
                      isAdvQuery: !sampleTable.isVoucher,
                      advQueryParams: [],
                      formQueryParams: getIniFormQueryParams(),
                    };

                    setFormQueryParams(propsOfParams.curWhereSqlParams.formQueryParams); //清空界面查询条件

                    //  refreshData(!sampleTable.isVoucher)
                  }
                }}
              />
            </div>
          </Item>

          <Item location="before" key="itemName">
            <div
              style={{
                alignItems: 'center',
                justifyContent: 'center',
                display: propsOfParams.curSampleTable.isVoucher ? 'none' : 'flex',
              }}
            >
              <div>抽样项目：</div>
              <TextBox
                value={propsOfParams.curSampleItem?.itemName}
                width={120}
                hint={propsOfParams.curSampleItem?.itemName}
                ref={itemNameRef}
                readOnly={propsOfParams.curSampleTable.isVoucher}
                onValueChanged={(e: any) => {
                  if (isOverallAddMode || isOverallEditMode) {
                    propsOfParams.curSampleItem.itemName = e.value;
                    propsOfParams.setCurSampleItem &&
                      propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });
                  }
                }}
              >
                <TextBoxButton
                  name="select"
                  location="after"
                  options={{
                    height: 28,
                    icon: 'more',
                    stylingMode: 'outlined', //'text' | 'outlined' | 'contained';
                    onClick: () => {
                      setIsNeedReportModal(true);
                      const interval = setInterval(() => {
                        if (reportModalRef.current) {
                          clearInterval(interval);
                          reportModalRef.current.show();
                        }
                      }, 10);
                    },
                  }}
                />
              </TextBox>
            </div>

            <div
              className="itemBoxDispaly"
              style={{
                marginBottom: '8px',
                display: propsOfParams.curSampleTable.isVoucher ? '' : 'none',
              }}
            >
              <div
                style={{
                  width: '66px',
                  margin: '0 5px',
                }}
              >
                科目名称<span style={{ color: 'red', fontSize: 14 }}>*</span>
              </div>
              <TextBox
                isValid={!!formQueryParams.kmmcStr}
                validationError={formQueryParams.kmmcStr ? '' : '请输入科目名称'}
                value={formQueryParams.kmmcStr}
                disabled={isAdvQuery}
                width={150}
                onValueChange={(value: any) => {
                  formQueryParams.kmmcStr = value;
                  changeFormQueryValue('kmmcStr', value);
                  if (isOverallAddMode || isOverallEditMode) {
                    propsOfParams.curSampleItem.itemName =
                      getItemNameByFormQueryParams(formQueryParams);
                    propsOfParams.setCurSampleItem &&
                      propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });
                  }
                }}
                onEnterKey={() => refreshData()}
                hint={consts.multiSeparator}
              >
                <TextBoxButton
                  name="text"
                  location="after"
                  options={{
                    height: 28,
                    icon: 'more',
                    stylingMode: 'outlined', //'text' | 'outlined' | 'contained';
                    onClick: () => {
                      setIsNeedSubject(true);
                      const interval = setInterval(() => {
                        if (subjectRef.current) {
                          clearInterval(interval);
                          subjectRef.current.show({
                            title: '选择科目',
                            dbname: dbname,
                            Data_ID: propsOfParams.curDataId,
                            isHasFZZ: false,
                            editUser: username,
                            // 选择 模式 0：单选 1：多选连机选择
                            selectMode: '1',
                            //  1：多选连机选择时是否进行递归选择默认是 true
                            recursiveMultiple: false,
                            // 是否为辅助账
                            auxiliaryState: false,
                            // 可以选择当前节点的科目
                            isSelectSuperior: false,
                            // 自动结转科目 默认选中的类型参数
                            subjectType: 'periodEarly',
                            okCallback: (r: any, v: any) => {
                              // 科目审定明细 界面增加一级科目在业务组件 需做更改
                              const kmmcData = v.map((item: any) => item.KMMC).join(',');

                              changeFormQueryValue('kmmcStr', kmmcData);
                              formQueryParams.kmmcStr = kmmcData;

                              if (isOverallAddMode || isOverallEditMode) {
                                propsOfParams.curSampleItem.itemName =
                                  getItemNameByFormQueryParams(formQueryParams);
                                propsOfParams.setCurSampleItem &&
                                  propsOfParams.setCurSampleItem({
                                    ...propsOfParams.curSampleItem,
                                  });
                              }

                              refreshData();
                            },
                          });
                        }
                      }, 10);
                    },
                  }}
                />
              </TextBox>
            </div>
          </Item>
          <Item location="before" key="assertion" locateInMenu={'auto'}>
            <div
              className="for-button-padding5"
              style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            >
              <div>认定：</div>
              <TagBox
                width={100}
                placeholder="请选择认定"
                searchEnabled={true}
                multiline={false}
                valueExpr="value"
                displayExpr="text"
                items={consts.assertions}
                value={propsOfParams.curSampleItem?.assertion}
                showSelectionControls={true}
                applyValueMode="useButtons"
                onValueChanged={(e: any) => {
                  if (isOverallAddMode || isOverallEditMode) {
                    propsOfParams.curSampleItem.assertion = e.value;
                    propsOfParams.setCurSampleItem &&
                      propsOfParams.setCurSampleItem({ ...propsOfParams.curSampleItem });
                  }
                }}
                maxDisplayedTags={1} //显示为第一项+等几项
                onMultiTagPreparing={(args: any) => tabBoxOnMultiTagPreparingOfProp(args, 'text')}
                dropDownOptions={{ minWidth: 150, width: 250 }}
              />
              {/*  <SelectBox
                            width={100}
                            placeholder='请选择认定'
                            dataSource={consts.assertions}
                            dropDownOptions={{ width: 150 }}
                            value={props.curSampleItem?.assertion}
                            hint={consts.assertions.find(item => item.value === props.curSampleItem?.assertion)?.text}
                            searchEnabled={true}
                            displayExpr="text"
                            valueExpr='value'
                            onValueChanged={(e: any) => {
                                props.curSampleItem.assertion = e.value;
                                props.setCurSampleItem && props.setCurSampleItem({ ...props.curSampleItem })
                            }}

                        /> */}
            </div>
          </Item>
          <Item location="before" key="textFieldsText" locateInMenu={'auto'}>
            <div style={{ marginLeft: 0, display: 'flex', alignItems: 'center' }}>
              <div>项目字段:</div>
              <TagBox
                width={150}
                placeholder="请选择字段"
                searchEnabled={true}
                multiline={false}
                valueExpr="fieldName"
                displayExpr="fieldTitle"
                items={propsOfParams.curSampleTable.sampleAllFieldsArray}
                value={propsOfParams.curSampleTable?.sampleTextFieldsArray}
                showSelectionControls={true}
                applyValueMode="useButtons"
                onValueChanged={async (e: any) => {
                  if (!e.event) return; //如果没有event,不是点击传入的,可能是别的调用导致的
                  if (propsOfParams.curSampleTable && propsOfParams.setCurSampleTable) {
                    // 获取抽样项目字段值是否唯一,不唯一不能选择
                    if (
                      e.value.length &&
                      !(await getTextFieldValueIsKeyOfMsg(
                        dbname,
                        propsOfParams.curSampleTable,
                        e.value,
                        propsOfParams.curDataId,
                      ))
                    ) {
                      return;
                    }
                    propsOfParams.curSampleTable.sampleTextFieldsArray = e.value;
                    propsOfParams.curSampleTable.sampleTextFields = e.value.join(',');

                    propsOfParams.setCurSampleTable({ ...propsOfParams.curSampleTable });

                    updateSampleTableProps(
                      propsOfParams.sampleTableList,
                      propsOfParams.curSampleTable,
                      'sampleTextFieldsArray',
                      e.value,
                    );

                    udpateSampleTableValue(
                      propsOfParams.sampleTableList,
                      propsOfParams.curSampleTable,
                      dbname,
                      'sampleTextFields',
                      e.value.join(','),
                    );
                    refreshData();
                  }
                }}
                maxDisplayedTags={1} //显示为第一项+等几项
                onMultiTagPreparing={(args: any) =>
                  tabBoxOnMultiTagPreparingOfProp(args, 'fieldTitle')
                }
                dropDownOptions={{ minWidth: 300, width: 400 }}
              />
              {/* <TextBox width={120} hint={textFieldsText} style={{ marginLeft: 5 }} value={textFieldsText} readOnly={true} /> */}
            </div>
          </Item>
          <Item location="before" key="numFieldsText" locateInMenu={'auto'}>
            <div style={{ marginLeft: 0, display: 'flex', alignItems: 'center' }}>
              <div>金额字段:</div>
              <TagBox
                width={150}
                placeholder="请选择字段"
                searchEnabled={true}
                multiline={false}
                valueExpr="fieldName"
                displayExpr="fieldTitle"
                items={propsOfParams.curSampleTable?.sampleAllFieldsArray?.filter(
                  (item) => item.isNum,
                )}
                value={propsOfParams.curSampleTable?.sampleNumFieldsArray}
                showSelectionControls={true}
                applyValueMode="useButtons"
                onValueChanged={(e: any) => {
                  if (!e.event) return; //如果没有event,不是点击传入的,可能是别的调用导致的
                  if (propsOfParams.curSampleTable && propsOfParams.setCurSampleTable) {
                    let values: string[] = e.value;
                    let isNeedMsg = false;

                    if (propsOfParams.curSampleTable.isCustom && values.length > 1) {
                      values = [values[0]]; //只保留一个
                      isNeedMsg = true;
                    }

                    propsOfParams.curSampleTable.sampleNumFieldsArray = values;
                    propsOfParams.curSampleTable.sampleNumFields = values.join(',');

                    propsOfParams.setCurSampleTable({ ...propsOfParams.curSampleTable });

                    updateSampleTableProps(
                      propsOfParams.sampleTableList,
                      propsOfParams.curSampleTable,
                      'sampleNumFieldsArray',
                      values,
                    );
                    updateSampleTableProps(
                      propsOfParams.sampleTableList,
                      propsOfParams.curSampleTable,
                      'sampleNumFields',
                      values.join(','),
                    );

                    //  props.setSampleStepInfo && props.setSampleStepInfo({ ...sampleStepInfo, projectOverallProps: propsOfParams })

                    udpateSampleTableValue(
                      propsOfParams.sampleTableList,
                      propsOfParams.curSampleTable,
                      dbname,
                      'sampleNumFields',
                      values.join(','),
                    );
                    if (isNeedMsg) {
                      msgError('自定义表只能选择一个金额字段');
                      return;
                    }
                    refreshData();
                  }
                }}
                maxDisplayedTags={1} //显示为第一项+等几项
                onMultiTagPreparing={(args: any) =>
                  tabBoxOnMultiTagPreparingOfProp(args, 'fieldTitle')
                }
                dropDownOptions={{ minWidth: 300, width: 400 }}
              />
              {/* <TextBox width={120} hint={numFieldsText} style={{ marginLeft: 5 }} value={numFieldsText} readOnly={true} /> */}
            </div>
          </Item>
        </Toolbar>

        <Collapse
          style={{
            marginTop: 5,
            marginBottom: 5,
            paddingTop: 0 /*  isOverallMode ? 8 : 0 */,
            borderRadius: 5,
          }}
          className="ant-collapse"
          onChange={(e) => setIsOpenQueryArea(e.length > 0)}
        >
          <Collapse.Panel
            header="查询条件"
            key="1"
            extra={getQueryExtra()}
            style={{ marginTop: -5, padding: 0 }}
          >
            <div style={{ height: '9.5vh', marginTop: 0 }}>{getSourceToolbar()}</div>
          </Collapse.Panel>
        </Collapse>

        <div className={`ProjectPopulationBox ${isAdvQuery ? 'ProjectPopulationBox130' : ''}`}>
          <DevGrid.MultipleTap
            className={` PaperDevSortableGrid devHeadersCenter `}
            height={
              isOpenQueryArea ? (isSelectMode || isSampleListManualAddMode ? '65%' : '75%') : '90%'
            }
            width="100%"
            id="devGriSampleSource"
            ref={devGridSampleSourceDataRef}
            dataSource={sampleSourceTableDataSource}
            keyExpr="rn"
            isRemote={true}
            columns={sampleSourceDataColumns} //不加这个,setSampleSourceDataColumns会导致这个报错
            showBorders={true}
            showRowLines={true}
            showColumnLines={true}
            allowColumnResizing={true}
            loadPanel={{ enabled: true/* , shading: true,shadingColor: 'rgba(0,0,0,0.3)'  */ }}
            columnMinWidth={30}
            defaultFocusedRowIndex={0}
            searchPanel={{ visible: false, width: 100 }}
            headerFilter={{
              width: 300,
              // height: window.innerHeight / 2,
              allowSearch: true,
              visible: true,
              texts: { ok: '确定' },
            }}
            disableFirstHeaderSearch={true}
            pager={getGridDefaultPageProps()}
            //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
            remoteOperations={{ paging: true, filtering: true, sorting: true }} //加这个才能支持远程分页 远程过滤 20230507
            sorting={{ mode: 'multiple' }} //shift多排序
            renderAsync={true}
            sheetName={propsOfParams.curSampleTable?.tableTitle}
            excelName={
              propsOfParams.curSampleTable?.tableTitle + '-' + formatDateYYMMDD(new Date())
            }
            selection={{ mode: 'none' }}
            onSelectionChanged={(e: any) => {
              propsOfParams.events?.onSelectionChanged &&
                propsOfParams.events.onSelectionChanged(e);
            }}
            onRowDblClick={(e: any) => {
              if (propsOfParams.events?.onRowDblClick) {
                propsOfParams.events.onRowDblClick(e);
              } else {
                if (propsOfParams.curSampleTable?.isVoucher) {
                  //双击打开 凭证
                  setIsNeedAccountingVouche(true);
                  const interval = setInterval(() => {
                    if (accountingVoucherPupopRef?.current) {
                      clearInterval(interval);
                      accountingVoucherPupopRef.current.showPupop(
                        {
                          ...e.data,
                          Data_ID: propsOfParams.curDataId,
                          dbname,
                          cancelCallback: () => setIsNeedAccountingVouche(false),
                        },
                        [],
                      );
                    }
                  }, 10);
                }
              }
            }}
            loadAllDevGridExport={async () => {
              //全部导出时的数据源
              setLoading(true);
              const rowsData: any = await getExportGridDataSource(dataParams, onBeforeExportData);
              setLoading(false);
              return { dataSource: rowsData };
            }}
          >
            <Paging enabled={true} defaultPageSize={consts.defaultSampePageSize} />
          </DevGrid.MultipleTap>
        </div>
        <LoadPanel visible={loading} />
      </div>
    );
  },
);
export default SamplingProjectOverall;
